<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use App\Repositories\MessageRepository;

class SendTemplateMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 1;

    private $key;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($key)
    {
        $this->key = $key;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $app = resolve(\EasyWeChat\MiniProgram\Application::class);
        $message = MessageRepository::findMessageByKey($this->key);
        $value = json_decode($message->value);

        if ($message->status === MessageRepository::MESSAGE_STATUS_WAIT_SEND) {

            // 发送微信模板消息
            $res = $app->template_message->send([
                'touser' => $message->wechatUser->openid,
                'template_id' => 'VTExm497yOc6YNRnVpy4xtw5kQWc9rHBKAQy759PxP0',
                'page' => '/pages/bet/bet?url=' . (route('quiz', ['quiz' => $value->id])),
                'form_id' => $message->form_id,
                'data' => [
                    'keyword1' => $value->name,
                    'keyword2' => __('generic.template_message_announce'),
                ],
            ]);
            if ($res['errcode'] != '0') {
                throw new \Exception($res['errmsg']);
            }
            $message->status = MessageRepository::MESSAGE_STATUS_HAS_SEND;
            $message->save();
        }
    }

    /**
     * @param \Exception $exception
     */
    public function failed(\Exception $exception)
    {
        Log::debug($exception->getMessage());
    }
}
